import {
  getRoleListReq,
  addOrEditRoleReq,
  delRoleReq,
  delRoleAuthReq,
  editRoleAuthReq,
} from '../request/role'

import { getAuthListReq } from '../request/auth'
const actions = {
  // 获取角色列表
  async getRoleList(context) {
    const roleListData = await getRoleListReq()
    // console.log(roleListData)
    context.commit('GET_ROLE_LIST', roleListData)
  },
  // 添加或编辑角色
  async addOrEditRole(context, { id, params }) {
    try {
      const addOrEditRoleData = await addOrEditRoleReq(id, params)
      return addOrEditRoleData
    } catch (error) {
      return Promise.reject(error)
    }
  },
  // 删除角色
  async delRole(context, id) {
    try {
      const delRoleData = await delRoleReq(id)
      return delRoleData
    } catch (error) {
      return Promise.reject(error)
    }
  },
  // 删除角色指定权限
  async delRoleAuth(context, { roleId, rightsId }) {
    try {
      const delRoleAuthData = await delRoleAuthReq(roleId, rightsId)
      return delRoleAuthData
    } catch (error) {
      return Promise.reject(error)
    }
  },
  // 获取树形权限列表
  async getAuthTree(context) {
    try {
      const authTreeList = await getAuthListReq('tree')
      context.commit('GET_AUTH_TREE', authTreeList)
    } catch (error) {
      return Promise.reject(error)
    }
  },
  // 角色授权
  async editRoleAuth(context, { roleId, rids }) {
    try {
      const editRoleAuthData = await editRoleAuthReq(roleId, rids)
      return editRoleAuthData
    } catch (error) {
      return Promise.reject(error)
    }
  },
}
const mutations = {
  GET_ROLE_LIST(state, roleList) {
    state.roleList = roleList
  },
  GET_AUTH_TREE(state, authTree) {
    state.authTree = authTree
  },
}
const state = {
  roleList: [], // 角色列表
  authTree: [], // 权限树形列表
}

export default {
  namespaced: true,
  actions,
  mutations,
  state,
}
